<?php
declare(strict_types=1);

namespace Service\MnBudgetService;

use App\Model\BbcModel\Mnuser;
use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\MnBudget;

class MnBudgetService extends BaseService
{
    
    const TYPE_INCOME       = 0;//收入
    const TYPE_EXPENDITURE  = 1;//支出
    
    const MONEY_TYPE_OLDDATA    = 0;//老数据
    const MONEY_TYPE_ORDER      = 1;//订单收入
    const MONEY_TYPE_MEMBER     = 2;//购买会员收入
    const MONEY_TYPE_BALANCE    = 3;//购买储值积分收入
    const MONEY_TYPE_WITHDRAW   = 4;//提现支出
    const MONEY_TYPE_ORDERRETURN= 5;//订单退款支出
    const MONEY_TYPE_OPENSTORE  = 6;//开店收入

        
    /**
     * 新增收益记录和收益
     * @param int $cid
     * @param int $mn_sid
     * @param int $mid
     * @param int $mnid
     * @param array $extra
     * @return array
     */
    public function addBudget(int $cid,int $mn_sid,int $mid,int $mnid,array $extra):array {
        if($extra['distribute_money']>0){
            $add_wallet_accumulate_income=Mnuser::instance()->where(['id'=>$mn_sid])->increment('wallet_accumulate_income',$extra['distribute_money']);
            if(!$add_wallet_accumulate_income){
                return Normal::returnCode(Normal::FAIL, '累计所有收益更新失败');
            }
            $add_wallet_income=Mnuser::instance()->where(['id'=>$mn_sid])->increment('wallet_income',$extra['distribute_money']);
            if(!$add_wallet_income){
                return Normal::returnCode(Normal::FAIL, '当前收益更新失败');
            }
            $add_all_sell=Mnuser::instance()->where(['id'=>$mn_sid])->increment('all_sell',$extra['distribute_money']);
            if(!$add_all_sell){
                return Normal::returnCode(Normal::FAIL, '累计销售额失败');
            }
        }
        $time=time();
        $budget=[
            'mnid'       => $mnid,
            'mn_sid'     => $mn_sid,
            'mid'        => 0,
            'type'       => $extra['type'],
            'money_type' => $extra['money_type'],
            'pay_type'   => $extra['pay_type'],
            'pay_serial' => $extra['pay_serial'],
            'sn'         => $extra['sn'],
            'goods_id'   => $extra['goods_id'],
            'money'      => $extra['channel_money'],
            'amount'     => $extra['channel_amount'],
            'cd'         => $time,
            'cid'        => $cid,
            'remark'     => $extra['remark']
        ];
        $budgetChannel = MnBudget::instance()->add($budget);
        if(!$budgetChannel){
            return Normal::returnCode(Normal::FAIL, '新增渠道收支记录失败');
        }
        $budget['mid']=$mid;
        $budget['cid']=0;
        $budget['money']=$extra['store_money'];
        $budget['amount']=$extra['store_amount'];
        $budgetStore=MnBudget::instance()->add($budget);
        if(!$budgetStore){
            return Normal::returnCode(Normal::FAIL, '新增店铺收支记录失败');
        }
        return Normal::returnCode(Normal::SUC, '操作成功');
    }
}
